package com.netty.io.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 将nio3的内容写进nio4里
 * FileInputStream和FileOutputStream分别获取channel
 * bytebuffer作为数据的桥梁
 * FileInputStream → InputChannel → buffer → outputChannel → FileOutputStream
 * */
public class NioCopyExample {

    public static void main(String[] args) throws Exception{
        File file = new File("/Users/xiaoqi/nio3.txt");
        FileInputStream inputStream = new FileInputStream(file);
        FileOutputStream outputStream = new FileOutputStream("/Users/xiaoqi/nio4.txt");
        FileChannel inputStreamChannel = inputStream.getChannel();
        FileChannel outputStreamChannel = outputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1000);
        while (true){

            //buffer第一次读完nio3的数据后，read为0，需将buffer复位，否则会一直将数据写入nio4文件
            byteBuffer.clear();
            int read = inputStreamChannel.read(byteBuffer);
            if(read != -1){
                byteBuffer.flip();
                outputStreamChannel.write(byteBuffer);
            }else {
                break;
            }
        }
        inputStream.close();
        outputStream.close();
    }
}
